package com.cupk.service.impl;

import com.cupk.mapper.MatchMapper;
import com.cupk.mapper.StudentMapper;
import com.cupk.pojo.Match;
import com.cupk.service.MatchService;
import com.cupk.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class MatchServiceImpl implements MatchService {
    @Autowired
    private MatchMapper matchMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Match> getMyList(Integer userId, String name) {
        return matchMapper.getMyList(userId, name);
    }

    @Override
    public List<Match> getAllList(String name) {
        return matchMapper.getAllList(name);
    }

    @Override
    public void addMatch(Match match) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        match.setUser(userId);
        matchMapper.addMatch(match);
    }

    @Override
    public List<Match> findSimilar(String name, Integer session) {
        return matchMapper.getMatchListByNameAndSession(name, session);
    }

    @Override
    public Match getMatchById(Integer id) {
        return matchMapper.getMatchById(id);
    }

    @Override
    public void updateMatch(Match match) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        match.setUser(userId);
        matchMapper.updateMatch(match);
    }

    @Override
    public List<Match> getAvailableList(LocalDateTime nowTime) {
        return matchMapper.getAvailableListByTime(nowTime);
    }

    @Override
    public Integer judgeBlackList(Integer userId) {
        return studentMapper.judgeBlackList(userId);
    }

    @Override
    public void deleteMatch(Integer matchId) {
        matchMapper.deleteMatch(matchId);
    }

    @Override
    public Match addStatus(Match m) {
        LocalDateTime startTime = m.getStartTime();
        LocalDateTime endTime = m.getEndTime();
        LocalDateTime nowTime = LocalDateTime.now();
        if (nowTime.isBefore(startTime)) {
            m.setStatus(0);   // 待开始
        } else if (nowTime.isAfter(endTime)) {
            m.setStatus(2);   // 已结束
        } else {
            m.setStatus(1);   // 进行中
        }
        return m;
    }
}
